package com.zklh.leetcode.interviewTop150;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 反转字符串中单词算法实现
 *
 * @Author tongnan
 * @Date 2024/6/13
 * @Version 1.0
 */
public class Solution151 {
    public String reverseWords(String s) {
        List<int[]> words = new ArrayList<>();
        char[] chars = s.toCharArray();
        int current = 0, start = -1, end = -1;
        while (current < chars.length) {
            if (chars[current] == ' ') {
                current++;
            } else {
                start = current;
                while (current < chars.length && chars[current] != ' ') {
                    end = current;
                    current++;
                }
                words.add(new int[]{start, end});
            }
        }
        StringBuilder result = new StringBuilder();
        for (int i = words.size() - 1; i >= 0; i--) {
            result.append(Arrays.copyOfRange(chars, words.get(i)[0], words.get(i)[1]+1));
            result.append(' ');
        }
        result.deleteCharAt(result.length()-1);
        return result.toString();
    }

    public static void main(String[] args) {
        Solution151 solution151 = new Solution151();
        System.out.println(solution151.reverseWords("the sky is blue"));
        System.out.println(solution151.reverseWords("  hello world  "));
        System.out.println(solution151.reverseWords("a good   example"));
    }
}